package com.icez.in_app_notication_library

import android.graphics.PixelFormat
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.lang.ref.WeakReference

class InAppNoticationManager : DefaultLifecycleObserver {

    companion object {
        //弱引用
        private var activityWeekReference: WeakReference<AppCompatActivity>? = null

        // 用于保存多个app内部通知
        private val inAppNotationMap: MutableMap<String, InAppNoticationManager> = mutableMapOf()


        /**
         * 创建内部通知
         * @sample
         * @author Icez
         */
        @JvmStatic
        fun create(activity: AppCompatActivity): InAppNoticationManager {
            //初始化app内部通知
            val inAppNoticationManager = InAppNoticationManager()
            //初始化布局，添加生命监听
            inAppNoticationManager.initLayoutAddLifecycleObserver(activity)
            Handler(Looper.getMainLooper()).post {
                inAppNotationMap[activity.toString()]?.inAppNoticationLayout?.let {
                    //map能找到内部通知
                    if (it.isAttachedToWindow) {//判断是否附加在窗口
                        //通知控件进行隐藏
                        ViewCompat.animate(it).alpha(0f).withEndAction {
                            if (it.isAttachedToWindow) {//判断通知控件是否附加在窗口
                                //窗口移除通知控件
                                activity.windowManager.removeViewImmediate(it)
                            }
                        }
                    }
                }
                //添加新的通知管理
                inAppNotationMap[activity.toString()] = inAppNoticationManager
            }
            return inAppNoticationManager
        }
    }

    //通知控件
    private var inAppNoticationLayout: InAppNoticationLayout? = null

    //窗口管理
    private var windowManager: WindowManager? = null

    //适配器
    private var inAppNoticationAdapter: InAppNoticationAdapter<*> ?= null

    private var activity:AppCompatActivity? = null

    /**
     * 初始化布局，添加生命监听
     * @sample
     * @author Icez
     */
    private fun initLayoutAddLifecycleObserver(activity: AppCompatActivity) {
        activityWeekReference = WeakReference(activity)
        inAppNoticationLayout = InAppNoticationLayout(activity)
        this.activity = activity
        windowManager = activity.windowManager
        activity.lifecycle.addObserver(this)
    }


    /**
     * 显示通知
     * @sample
     * @author Icez
     */
    fun <B:ViewDataBinding> show(inAppNoticationAdapter: InAppNoticationAdapter<B>) {
        try {
            this.inAppNoticationAdapter = inAppNoticationAdapter
            inAppNoticationLayout?.removeAllViews()
            inAppNoticationLayout?.setOnTouchDismiss(inAppNoticationAdapter.onTouchDismissDirection())
            var layout = activity?.let { inAppNoticationAdapter.getBinding(it).root }
            inAppNoticationLayout?.addView(layout)
            windowManager?.addView(inAppNoticationLayout, initLayoutParameter())

            var duration = this.inAppNoticationAdapter!!.onStayDuration()
            if(duration<=0){
                duration = InAppNoticationLayout.ANIMATION_DURATION*6
            }

            inAppNoticationLayout?.postDelayed({
                // 隐藏
                inAppNoticationLayout?.hide(false)
            },duration )
            inAppNoticationLayout?.setOnClickListener {
                //隐藏
                inAppNoticationLayout?.hide(true)
                this.inAppNoticationAdapter!!.onItemClick()
            }
        } catch (err: Exception) {

        }
    }

    /**
     * 初始化通知控件参数
     * @sample
     * @author Icez
     */
    private fun initLayoutParameter(): WindowManager.LayoutParams {
        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            0,
            0,
            PixelFormat.TRANSLUCENT
        )

        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        layoutParams.gravity = Gravity.TOP

        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM

        layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL

        return layoutParams

    }


    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
    }


}